'use strict';

const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  console.log('获取纠纷处理记录云函数被调用，参数:', event)
  
  // 管理员访问检查
  const isAdminAccess = event.isAdmin || false
  let uid = null
  
  if (!isAdminAccess) {
    const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
    if (!token) {
      return { code: 401, msg: '未登录' }
    }
    
    const uniId = uniIdCommon.createInstance({ context })
    const tokenRes = await uniId.checkToken(token)
    if (tokenRes.code !== 0) {
      return { code: 401, msg: 'token无效或已过期' }
    }
    uid = tokenRes.uid
    
    // 检查是否是管理员
    const userInfo = tokenRes.userInfo
    if (!userInfo || userInfo.role !== 'admin') {
      return { code: 403, msg: '无权访问，仅限管理员' }
    }
  } else {
    console.log('管理员访问，跳过token验证')
    uid = 'admin'
  }

  const { page = 1, pageSize = 20, action, startDate, endDate } = event
  
  const db = uniCloud.database()
  const dbCmd = db.command
  
  try {
    // 构建查询条件
    let where = {}
    
    // 按操作类型筛选
    if (action) {
      where.action = action
    }
    
    // 按日期范围筛选
    if (startDate || endDate) {
      where.timestamp = {}
      if (startDate) {
        where.timestamp[dbCmd.gte] = new Date(startDate).getTime()
      }
      if (endDate) {
        where.timestamp[dbCmd.lte] = new Date(endDate + ' 23:59:59').getTime()
      }
    }
    
    // 查询纠纷处理记录
    const disputeCollection = db.collection('dispute_logs')
    
    // 获取总数
    const countResult = await disputeCollection.where(where).count()
    const total = countResult.total
    
    // 分页查询
    const skip = (page - 1) * pageSize
    const result = await disputeCollection
      .where(where)
      .orderBy('timestamp', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()
    
    console.log(`查询到${result.data.length}条纠纷处理记录`)
    
    let records = result.data
    
    // 如果有记录，补充任务信息（发布者和接单人）
    if (records.length > 0) {
      const taskIds = [...new Set(records.map(r => r.task_id).filter(id => id))]
      
      if (taskIds.length > 0) {
        console.log('查询任务信息，任务数量:', taskIds.length)
        
        // 查询任务信息
        const tasksResult = await db.collection('taskList')
          .where({
            _id: db.command.in(taskIds)
          })
          .field({
            _id: true,
            title: true,
            publisher_id: true,
            publisher_name: true,
            receiver_id: true,
            receiver_name: true
          })
          .get()
        
        console.log('查询到任务信息:', tasksResult.data.length, '条')
        
        // 构建任务信息映射
        const tasksMap = {}
        tasksResult.data.forEach(task => {
          tasksMap[task._id] = task
        })
        
        // 合并任务信息到记录中
        records = records.map(record => {
          const task = tasksMap[record.task_id]
          
          return {
            _id: record._id,
            task_id: record.task_id,
            task_title: record.task_title || (task ? task.title : '未知任务'),
            action: record.action,
            reason: record.reason,
            admin_id: record.admin_id,
            admin_name: record.admin_name || '管理员',
            original_status: record.original_status,
            new_status: record.new_status,
            result_message: record.result_message,
            process_time: record.timestamp,
            create_time: record.create_time,
            // 优先使用记录中的，如果没有则从任务中获取
            publisher_name: record.publisher_name || (task ? task.publisher_name : null) || '未知用户',
            receiver_name: record.receiver_name || (task ? task.receiver_name : null),
            // 通知状态（如果有）
            notification_status: record.notification_status || null
          }
        })
      } else {
        // 没有任务ID，直接返回原始记录
        records = records.map(record => ({
          _id: record._id,
          task_id: record.task_id,
          task_title: record.task_title,
          action: record.action,
          reason: record.reason,
          admin_id: record.admin_id,
          admin_name: record.admin_name || '管理员',
          original_status: record.original_status,
          new_status: record.new_status,
          result_message: record.result_message,
          process_time: record.timestamp,
          create_time: record.create_time,
          publisher_name: record.publisher_name || '未知用户',
          receiver_name: record.receiver_name || null,
          notification_status: record.notification_status || null
        }))
      }
    }
    
    const totalPages = Math.ceil(total / pageSize)
    
    return {
      code: 200,
      msg: '获取成功',
      data: {
        records: records,
        page: page,
        pageSize: pageSize,
        total: total,
        totalPages: totalPages
      }
    }
    
  } catch (error) {
    console.error('获取纠纷处理记录失败:', error)
    return {
      code: 500,
      msg: '获取纠纷处理记录失败: ' + error.message,
      error: error.toString()
    }
  }
}

